﻿#include"stdafx.h"
#include"SQLexpression.h"
bool SqlEx::ForCreateDB()
{
	string msg = "";
	if (!authority->isRoot(user_host)) {
		msg = "You do not have permission to create a database !";
	}
	else {
		string str;
		regex reg1("(?<=create database ).+(?=END)");
		smatch sm;
		if (regex_search(Ex, sm, reg1)) {
			str = sm.str();
			int lenth = str.length();
			char *db = new char[lenth + 1];
			memset(db, 0, lenth + 1);
			memcpy(db, str.c_str(), lenth);
			serverDB->DB_Create(db, msg);
			delete db;
		}
	}
	pSocket->SendMSG(msg);
	return true;
}

bool SqlEx::ForShowDB()
{
	//返回所有当前用户有权限的数据库名称
	string msg = "";
	vector<string>info;
	if (serverDB->DB_Show(info)) {
		for (unsigned int i = 0; i < info.size(); i++) {
			if (authority->Auth_Judge(user_host, info[i], "")) {
				msg += info[i] + "\n";
			}
			else if (info[i] != "system") {
				vector<string>tables;
				serverDB->Table_show(tables, info[i]);
				for (unsigned int j = 0; j < tables.size(); j++) {
					if (authority->Auth_Judge(user_host, info[i], tables[j])) {
						msg += info[i] + "\n";
						break;
					}
				}
			}

		}
	}
	else {
		msg = "Some unpredictable things happened !";
	}
	if (msg == "")
		msg = "No databases you can access !";
	pSocket->SendMSG(msg);
	return true;
}

bool SqlEx::ForDropDB()
{
	string msg = "";
	string str;
	regex reg1("(?<=drop database ).+(?=END)");
	smatch sm;
	if (regex_search(Ex, sm, reg1)) {
		str = sm.str();
		if (!authority->dropDB(user_host, str)) {
			msg = "You do not have permission to drop the database !";
		}
		else {
			int lenth = str.length();
			char *db = new char[lenth + 1];
			memset(db, 0, lenth + 1);
			memcpy(db, str.c_str(), lenth);
			serverDB->DB_Drop(db, msg);
			CString csdb;
			csdb = db;
			if (pSocket->cur_db == csdb)
				pSocket->cur_db = L"";
			delete db;
		}
	}
	pSocket->SendMSG(msg);
	return true;
}

bool SqlEx::ForUseDB()
{
	string msg = "";
	string str;
	CString oldDB;
	oldDB = pSocket->cur_db;
	pSocket->cur_db = "";
	regex reg1("(?<=use ).+(?=END)");
	smatch sm;
	if (regex_search(Ex, sm, reg1)) {
		str = sm.str();
		if (str == "system") {
			pSocket->SendMSG("Database does not exist!");
			return false;
		}
		if (this->authority->Auth_Judge(user_host, str, "")) {
			pSocket->cur_db = str.c_str();
		}
		else {
			vector<string>tables;
			serverDB->Table_show(tables, str);
			for (unsigned int j = 0; j < tables.size(); j++) {
				if (authority->Auth_Judge(user_host, str, tables[j])) {
					pSocket->cur_db = str.c_str();
					break;
				}
			}
		}

		if (pSocket->cur_db == "") {
			msg = "You do not have permission to use the database !";
			pSocket->cur_db = oldDB;
		}
		else {
			int lenth = str.length();
			char *db = new char[lenth + 1];
			memset(db, 0, lenth + 1);
			memcpy(db, str.c_str(), lenth);
			if (!serverDB->DB_Use(db, msg))
				pSocket->cur_db = oldDB;
			delete db;
		}

	}
	else {
		msg = "检查你的sql语句！";
	}
	pSocket->SendMSG(msg);
	return true;
}